package com.yuanss.backenddemo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;

/**
 * @author yuanss
 * @version 1.0
 * @description jwt工具类
 * @date 2024/6/12 20:18:25
 */
//@Component
    @Slf4j
public class JWTUtils {

//    /**
//     * 密钥
//     */
//    @Value("${jwt.secret}")
//    private String secret;

    /**
     * 密钥
     * */
    private static final String secret = "889556654";

    /**
     * 生成token
     */
    public static String createToken(String username, String password) {
        try {
            //设置token时间 三小时
            Calendar nowTime = Calendar.getInstance();
            nowTime.add(Calendar.HOUR, 3);
            Date date = nowTime.getTime();

            //密文生成
            String token = JWT.create()
                    .withClaim("username", username)
                    .withClaim("password", password)
                    .withExpiresAt(date)
                    .withIssuedAt(new Date())
                    .sign(Algorithm.HMAC256(secret));
            return token;
        } catch (UnsupportedEncodingException e) {
            log.error("token生成失败，出现编码格式异常");
            throw new RuntimeException(e);
        }
    }

    /**
     * 验证token的有效性
     */
    public static boolean verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            verifier.verify(token);
            return true;
        } catch (UnsupportedEncodingException e) {
            return false;
        }
    }

    /**
     * 获取token列名
     * **/
    /**
     * 通过载荷名字获取载荷的值
     */

    public static String getClaim(String token, String name) {
        String claim = null;
        try {
            claim = JWT.decode(token).getClaim(name).asString();
        } catch (Exception e) {
            return "getClaimFalse";
        }
        return claim;
    }
}
